<template>
  <div class="find" :class="{ 'dark-mode': isDarkMode }">
    <header>
      <div class="logo">
        <img src="@/assets/img/logo/logo.png" alt="">
      </div>
      <div class="search-bar" @click="handleSearch">
        <van-icon name="search" />
        <span>搜索视频、创作者</span>
      </div>
    </header>

    <div class="find-content">
      <!-- 热门视频区域 -->
      <div class="section">
        <div class="section-header">
          <h3>热门推荐</h3>
          <van-icon name="fire-o" color="#ff6b6b" />
        </div>
        <div class="hot-videos">
          <div class="video-card" v-for="(item, index) in hotVideos" :key="index" @click="handleVideoClick(item)">
            <div class="video-cover">
              <img :src="item.cover.feed" alt="">
              <van-icon name="play-circle-o" color="#fff" size="25" />
              <div class="video-duration">{{ formatDuration(item.duration) }}</div>
            </div>
            <div class="video-info">
              <div class="video-title">{{ item.title }}</div>
              <div class="video-meta">
                <span class="author">{{ item.author?.name }}</span>
                <span class="stats">
                  <van-icon name="eye-o" size="12" />
                  {{ formatCount(item.consumption?.collectionCount) }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 本周排行榜区域 -->
      <div class="section">
        <div class="rank-section">
          <div class="rank-header">
            <h3>本周排行榜</h3>
            <div class="view-all" @click="handleRankClick">
              <span>全部</span>
              <van-icon name="arrow" />
            </div>
          </div>
          <div class="rank-content">
            <div class="rank-list">
              <div v-for="(item, index) in rankList" :key="item.id || index" class="rank-item"
                @click="handleRankItemClick(item)">
                <div class="rank-thumbnail-container">
                  <img :src="item.cover?.feed || getDefaultCover()" :alt="item.title" class="rank-thumbnail-img" />
                  <div class="rank-badge" :class="`rank-${index + 1}`">
                    No.{{ index + 1 }}
                  </div>
                </div>
                <span class="rank-title">{{ item.title }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频流区域 -->
      <div class="section">
        <div class="section-header">
          <h3>精选内容</h3>
        </div>
        <div class="video-list">
          <div class="video-item" v-for="(item, index) in videoList" :key="index" @click="handleVideoClick(item)">
            <div class="item-cover">
              <img :src="item.cover.feed" alt="">
              <van-icon name="play" color="#fff" size="30" />
            </div>
            <div class="item-details">
              <div class="item-title">{{ item.title }}</div>
              <div class="item-desc">{{ item.description || '暂无描述' }}</div>
              <div class="item-footer">
                <div class="author">
                  <div class="author-avatar" :style="{ backgroundImage: `url(${item.author?.icon})` }"></div>
                  <span>{{ item.author?.name }}</span>
                </div>
                <div class="stats">
                  <span><van-icon name="good-job-o" />{{ formatCount(item.consumption?.collectionCount) }}</span>
                  <span><van-icon name="chat-o" />{{ formatCount(item.consumption?.replyCount) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <van-loading v-if="loading" class="loading" type="spinner" color="#1989fa" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getHot, getSelected, getRankListWeekly } from '@/api/api';
import { useVideoStore } from '@/stores/counter';
import { useDarkModeStore } from '@/stores/darkMode';
import { showToast } from 'vant';

// 路由和 store
const router = useRouter();
const videoStore = useVideoStore();
const darkModeStore = useDarkModeStore();
const isDarkMode = computed(() => darkModeStore.isDarkMode);

// 数据状态
const hotVideos = ref<any[]>([]);
const videoList = ref<any[]>([]);
const rankList = ref<any[]>([]);
const loading = ref(false);

// 格式化时长
const formatDuration = (seconds: number): string => {
  if (!seconds || seconds < 0) return '00:00';
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
};

// 格式化数字
const formatCount = (count: number): string => {
  if (!count) return '0';
  if (count >= 10000) return `${(count / 10000).toFixed(1)}万`;
  return count.toString();
};

// 获取默认封面
const getDefaultCover = (): string => {
  return ''
};

// 视频点击事件
const handleVideoClick = (video: any) => {
  // 将当前点击的视频数据存入 store
  videoStore.setCurrentVideo(video);
  // 跳转到视频页面
  router.push('/video');
};

// 处理搜索点击
const handleSearch = () => {
  showToast({
    message: '搜索功能暂未开放',
    position: 'top',
  });
};

// 处理排行榜点击
const handleRankClick = () => {
  router.push('/rank');
};

// 处理排行榜项点击
const handleRankItemClick = (item: any) => {
  handleVideoClick(item);
};

// 获取热门视频数据
const fetchHotVideos = async () => {
  try {
    const data: any = await getHot();
    if (data.itemList && data.itemList.length > 0) {
      // 提取热门视频
      const videos: any[] = [];
      data.itemList.forEach((item: any) => {
        if (item.type === 'video' && videos.length < 6) {
          videos.push(item.data);
        }
      });
      hotVideos.value = videos;
    }
  } catch (err) {
    console.error('获取热门视频失败:', err);
  }
};

// 获取视频列表
const fetchVideoList = async () => {
  try {
    const data: any = await getSelected();
    if (data.itemList && data.itemList.length > 0) {
      // 提取视频数据
      videoList.value = [];
      data.itemList.forEach((item: any) => {
        if (item.type === 'video') {
          videoList.value.push(item.data);
        }
      });
    }
  } catch (err) {
    console.error('获取视频列表失败:', err);
  }
};

// 获取排行榜数据
const fetchRankList = async () => {
  try {
    const data: any = await getRankListWeekly();
    if (data.itemList && data.itemList.length > 0) {
      // 提取前3个视频作为排行榜预览
      const ranks: any[] = [];
      data.itemList.forEach((item: any) => {
        if (item.type === 'video' && ranks.length < 3) {
          ranks.push(item.data);
        }
      });
      rankList.value = ranks;
    }
  } catch (err) {
    console.error('获取排行榜失败:', err);
  }
};

// 获取发现页数据
const fetchFindData = async () => {
  loading.value = true;
  try {
    await Promise.all([fetchHotVideos(), fetchVideoList(), fetchRankList()]);
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchFindData();
});
</script>

<style scoped lang="less">
.find {
  width: 100%;
  min-height: 100vh;
  padding-bottom: 7vh;
  box-sizing: border-box;
  background-color: #fff;
  color: #000;
  transition: background-color 0.3s ease, color 0.3s ease;

  &.dark-mode {
    background-color: #000;
    color: #fff;
  }
}

header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 6vh;
  display: flex;
  align-items: center;
  gap: 3vw;
  box-shadow: 0 2px 2px 0 #0000001a;
  padding: 0 5vw;
  box-sizing: border-box;
  background-color: #fff;
  color: #000;
  z-index: 100;
  transition: background-color 0.3s ease, color 0.3s ease, box-shadow 0.3s ease;

  .logo {
    height: 50%;

    img {
      height: 100%;
    }
  }

  .search-bar {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 2vw;
    background: #f5f5f5;
    padding: 1vh 3vw;
    box-sizing: border-box;
    border-radius: 20px;
    cursor: pointer;

    span {
      font-size: 12px;
      color: #999;
    }
  }
}

.find-content {
  width: 100%;
  padding: 2vh 4vw;
  padding-top: calc(6vh + 2vh);
  box-sizing: border-box;

  .section {
    margin-bottom: 3vh;

    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 2vh;

      h3 {
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
}

.hot-videos {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 2vh 3vw;

  .video-card {
    cursor: pointer;
    transition: transform 0.2s;

    &:active {
      transform: scale(0.95);
    }

    .video-cover {
      position: relative;
      width: 100%;
      aspect-ratio: 16/9;
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 1vh;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      >i {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0.9;
      }

      .video-duration {
        position: absolute;
        bottom: 6px;
        right: 6px;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 6px;
        box-sizing: border-box;
        border-radius: 4px;
        font-size: 10px;
      }
    }

    .video-info {
      .video-title {
        line-height: 1.5;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 0.5vh;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .video-meta {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 10px;
        color: #999;

        .stats {
          display: flex;
          align-items: center;
          gap: 2px;
        }
      }
    }
  }
}

.video-list {
  display: flex;
  flex-direction: column;
  gap: 3vh;

  .video-item {
    display: flex;
    gap: 3vw;
    cursor: pointer;
    transition: transform 0.2s;

    &:active {
      transform: scale(0.98);
    }

    .item-cover {
      position: relative;
      width: 40%;
      aspect-ratio: 16/9;
      border-radius: 8px;
      overflow: hidden;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      >i {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0.9;
      }
    }

    .item-details {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .item-title {
        line-height: 1.5;
        font-size: 14px;
        font-weight: 500;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 1vh;
      }

      .item-desc {
        font-size: 11px;
        color: #666;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
        margin-bottom: 1vh;
      }

      .item-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 10px;
        color: #999;

        .author {
          display: flex;
          align-items: center;
          gap: 6px;

          .author-avatar {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-size: cover;
            background-position: center;
          }
        }

        .stats {
          display: flex;
          align-items: center;
          gap: 1vh;

          span {
            display: flex;
            align-items: center;
            gap: 2px;
          }
        }
      }
    }
  }
}

.loading {
  display: flex;
  justify-content: center;
  padding: 4vh 0;
}

.rank-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 2vh 3vw;
  box-sizing: border-box;

  .rank-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 2vh;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .view-all {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #999;
      font-size: 12px;
      cursor: pointer;
      transition: color 0.2s;

      &:active {
        color: #666;
      }

      i {
        font-size: 12px;
      }
    }
  }

  .rank-content {
    .rank-list {
      display: flex;
      flex-direction: column;
      gap: 2vh;

      .rank-item {
        display: flex;
        align-items: center;
        gap: 3vw;
        cursor: pointer;
        padding: 0.5vh 0;
        transition: opacity 0.2s;

        &:active {
          opacity: 0.6;
        }

        .rank-thumbnail-container {
          position: relative;
          width: 30vw;
          aspect-ratio: 16 / 9;
          border-radius: 8px;
          overflow: hidden;
          flex-shrink: 0;
          background-color: #f5f5f5;

          .rank-thumbnail-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .rank-badge {
            position: absolute;
            top: 0;
            left: 0;
            padding: 3px 6px;
            font-size: 11px;
            font-weight: 600;
            color: #fff;
            border-top-left-radius: 8px;
            border-bottom-right-radius: 8px;
            z-index: 2;
            background-color: #999;

            &.rank-1 {
              background-color: #ff6b6b;
            }

            &.rank-2 {
              background-color: #ffa726;
            }

            &.rank-3 {
              background-color: #ffca28;
            }
          }
        }

        .rank-title {
          font-size: 13px;
          color: #666;
          flex: 1;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

.find.dark-mode {
  header {
    background-color: #000;
    color: #fff;
    box-shadow: 0 2px 2px 0 rgba(255, 255, 255, 0.1);

    .search-bar {
      background: #333;

      span {
        color: #ccc;
      }
    }
  }

  .find-content {
    .section-header {
      h3 {
        color: #fff;
      }
    }

    .section {

      .video-card,
      .video-item {

        .video-info,
        .item-details {

          .video-title,
          .item-title {
            color: #fff;
          }

          .video-meta,
          .item-footer {
            color: #ccc;
          }
        }
      }

      .rank-section {
        background-color: #1a1a1a;

        .rank-header {
          h3 {
            color: #fff;
          }

          .view-all {
            color: #ccc;

            span {
              color: #ccc;
            }

            &:active {
              color: #999;
            }
          }
        }

        .rank-item {
          .rank-thumbnail-container {
            background-color: #333;
          }

          .rank-title {
            color: #fff;
          }
        }
      }
    }
  }
}
</style>
